import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 全局状态
    isLoading: false,
    networkType: 'unknown',
    platformName: '星点互助帮', // 平台名称（小程序初始化时从后端获取）
    // 未读数（用户/商家）
    userUnreadCount: 0,
    merchantUnreadCount: 0
  },
  mutations: {
    // 全局状态变更
    SET_LOADING(state, isLoading) {
      state.isLoading = isLoading
    },
    SET_NETWORK_TYPE(state, type) {
      state.networkType = type
    },
    setPlatformName(state, name) {
      state.platformName = name
    },
    // 未读数相关
    SET_USER_UNREAD_COUNT(state, count) {
      state.userUnreadCount = Number(count) || 0
    },
    SET_MERCHANT_UNREAD_COUNT(state, count) {
      state.merchantUnreadCount = Number(count) || 0
    },
    DECREMENT_USER_UNREAD_COUNT(state, step = 1) {
      const s = Number(step) || 1
      state.userUnreadCount = Math.max(0, (state.userUnreadCount || 0) - s)
    },
    DECREMENT_MERCHANT_UNREAD_COUNT(state, step = 1) {
      const s = Number(step) || 1
      state.merchantUnreadCount = Math.max(0, (state.merchantUnreadCount || 0) - s)
    },
    CLEAR_UNREAD_COUNTS(state) {
      state.userUnreadCount = 0
      state.merchantUnreadCount = 0
    }
  },
  actions: {
    // 获取网络状态
    getNetworkType({ commit }) {
      uni.getNetworkType({
        success: (res) => {
          commit('SET_NETWORK_TYPE', res.networkType)
        }
      })
    },
    // 初始化未读数（进入小程序时调用，一次拉取）
    async initUnreadCounts({ commit }) {
      try {
        const token = uni.getStorageSync('ss_satoken')
        if (!token) {
          commit('SET_USER_UNREAD_COUNT', 0)
          commit('SET_MERCHANT_UNREAD_COUNT', 0)
          return
        }
        // 动态引入，避免循环依赖
        const { getUnreadCount } = require('@/api/message')
        const { getMerchantUnreadCount } = require('@/api/merchant-message')

        const results = await Promise.allSettled([
          getUnreadCount(),
          getMerchantUnreadCount()
        ])

        // 用户未读数
        if (results[0].status === 'fulfilled') {
          commit('SET_USER_UNREAD_COUNT', results[0].value || 0)
        } else {
          commit('SET_USER_UNREAD_COUNT', 0)
        }

        // 商家未读数（普通用户会失败，这里吞掉）
        if (results[1].status === 'fulfilled') {
          commit('SET_MERCHANT_UNREAD_COUNT', results[1].value || 0)
        } else {
          commit('SET_MERCHANT_UNREAD_COUNT', 0)
        }
      } catch (e) {
        commit('SET_USER_UNREAD_COUNT', 0)
        commit('SET_MERCHANT_UNREAD_COUNT', 0)
      }
    }
  },
  modules: {
    user
  }
})
